<?php

namespace App\Http\Controllers\Order;

use App\Http\Controllers\BaseController;
use App\Models\Chanjet\TplusSaleInvoice;
use App\Models\Chanjet\TplusSaleInvoiceInfo;
use App\Models\Order\Outboundordersub;
use App\Models\Order\Saleimplementation;
use App\Models\Balance\Balance;
use App\Models\Order\Saleimplementationsub;
use App\Models\Order\Saleordersub;
use App\Models\Order\Salesorder;
use App\Models\Order\Salesordersub;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Models\Salerule\Salerule;

/**
 * 销售订单执行模块
 */
class SaleimplementationController extends BaseController
{
    /**
     * 列表
     */
    public function getlist(Request $request)
    {
        $memberinfo = $this->mangerinfo;
        $isgetall = $request->isgetall ?? 0;
        $list = Saleimplementation::getList($request, $memberinfo, $isgetall);
        if ($list['list']) foreach ($list['list'] as $key => $value) {
            $list['list'][$key]['sale_amount'] = mathfuncmoney('div', $value['sale_amount'], 100, 2);
            $list['list'][$key]['sale_weight'] = mathfuncweight('div', $value['sale_weight'], 10000, 4);
            $list['list'][$key]['sales_amount'] = mathfuncmoney('div', $value['sales_amount'], 100, 2);
            $list['list'][$key]['sales_weight'] = mathfuncweight('div', $value['sales_weight'], 10000, 4);
            $list['list'][$key]['outbound_amount'] = mathfuncmoney('div', $value['outbound_amount'], 100, 2);
            $list['list'][$key]['outbound_weight'] = mathfuncweight('div', $value['outbound_weight'], 10000, 4);

            $residue_amount = mathfuncmoney('div', ($value['sale_amount']-$value['sales_amount']), 100, 2);
            $list['list'][$key]['residue_amount'] =  round($residue_amount,2)?? 0;

            $residue_weight = mathfuncweight('div', ($value['sale_weight']-$value['sales_weight']), 10000, 4);
            //$residue_weight = mathfuncweight('div',($value['sale_weight'] - $value['sales_weight']),10000, 4);
            $list['list'][$key]['residue_weight'] = round($residue_weight,4)??0;

            $residue_pieces = $value['sale_pieces'] - $value['sales_pieces'];
            $list['list'][$key]['residue_pieces'] = $residue_pieces ?? 0;


            if ($value['suborder']) foreach ($value['suborder'] as $k => $v) {
                $list['list'][$key]['suborder'][$k]['outbound_amount'] = mathfuncmoney('div', $v['outbound_amount'], 100, 2);
                $list['list'][$key]['suborder'][$k]['outbound_weight'] = mathfuncweight('div', $v['outbound_weight'], 10000, 4);

                $residue_amount = mathfuncmoney('div', $v['sale_amount'], 100, 2) - mathfuncmoney('div', $v['sales_amount'], 100, 2);
                $list['list'][$key]['suborder'][$k]['residue_amount'] = round($residue_amount,2)?? 0;

                $residue_weight = mathfuncweight('div', $v['sale_weight'], 10000, 4) - mathfuncweight('div', $v['sales_weight'], 10000, 4);
                $list['list'][$key]['suborder'][$k]['residue_weight'] =  round($residue_weight,4)??0;

                $residue_pieces = $v['sale_pieces'] - $v['sales_pieces'];
                $list['list'][$key]['suborder'][$k]['residue_pieces'] = $residue_pieces ?? 0;

                $list['list'][$key]['suborder'][$k]['sale_amount'] = mathfuncmoney('div', $v['sale_amount'], 100, 2);
                $list['list'][$key]['suborder'][$k]['sale_weight'] = mathfuncweight('div', $v['sale_weight'], 10000, 4);
                $list['list'][$key]['suborder'][$k]['sales_amount'] = mathfuncmoney('div', $v['sales_amount'], 100, 2);
                $list['list'][$key]['suborder'][$k]['sales_weight'] = mathfuncweight('div', $v['sales_weight'], 10000, 4);

                $list['list'][$key]['suborder'][$k]['unit_price'] = mathfuncmoney('div', $v['unit_price'], 100, 2);
                $list['list'][$key]['suborder'][$k]['total'] = mathfuncmoney('div', $v['total'], 100, 2);

            }
        }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    /**
     * 详情
     */
    public function getone(Request $request)
    {
        $id = $request->id ?? 0;
        $one = Saleimplementation::getone($id);
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        }
        $one = $one->toArray();
        if ($one[0]) {
            $one[0]['sale_weight'] = $one[0]['sale_weight'] / 10000;
            $one[0]['sale_amount'] = $one[0]['sale_amount'] / 100;

            $one[0]['sales_weight'] = $one[0]['sales_weight'] / 10000;
            $one[0]['sales_amount'] = $one[0]['sales_amount'] / 100;

            $one[0]['outbound_weight'] = $one[0]['outbound_weight'] / 10000;
            $one[0]['outbound_amount'] = $one[0]['outbound_amount'] / 100;

            $one[0]['residue_weight'] = round($one[0]['sale_weight'] - $one[0]['sales_weight'],4)??0;
            $one[0]['residue_amount'] = round($one[0]['sale_amount'] - $one[0]['sales_amount'],2)??0;
            $one[0]['residue_pieces'] = $one[0]['sale_pieces'] - $one[0]['sales_pieces'];
        }

        if ($one[0]['suborder']) foreach ($one[0]['suborder'] as $key => $value) {
            $one[0]['suborder'][$key]['weight'] = $value['weight'] / 10000;
            $one[0]['suborder'][$key]['unit_price'] = $value['unit_price'] / 100;
            $one[0]['suborder'][$key]['total'] = $value['total'] / 100;

            $one[0]['suborder'][$key]['sale_weight'] = $value['sale_weight'] / 10000;
            $one[0]['suborder'][$key]['sale_amount'] = $value['sale_amount'] / 100;

            $one[0]['suborder'][$key]['sales_weight'] = $value['sales_weight'] / 10000;
            $one[0]['suborder'][$key]['sales_amount'] = $value['sales_amount'] / 100;

            $one[0]['suborder'][$key]['outbound_weight'] = $value['outbound_weight'] / 10000;
            $one[0]['suborder'][$key]['outbound_amount'] = $value['outbound_amount'] / 100;

            $one[0]['suborder'][$key]['residue_weight'] = round($one[0]['suborder'][$key]['sale_weight'] - $one[0]['suborder'][$key]['sales_weight'],4)?? 0;
            $one[0]['suborder'][$key]['residue_amount'] =  round($one[0]['suborder'][$key]['sale_amount'] - $one[0]['suborder'][$key]['sales_amount'],2)??0;
            $one[0]['suborder'][$key]['residue_pieces'] = $value['sale_pieces'] - $value['sales_pieces'];
        }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $one]);
    }

    /**
     * 结算
     *
     * 销售订单执行表, 结束时， 校准 销售结算单金额，
     * 发货时扣除余额是大概值，销售流扣除 余额后，多退少补。 2025.05.22 王丹娜
     * 可为负值
     *
     * 点价订单 order_type=4,每次回调销售发票扣余额，这里不用扣
     *
     * 销售订单执行表，完结。增加库存返还逻辑 2025.07.11 程阳
     *
     *
     */
    public function handlesettle(Request $request)
    {
        $id = $request->id ?? 0;
        $one = Saleimplementation::where('id', $id)->first();
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        } else {
            $one = $one->toArray();
            if ($one['is_sync'] == 1) {
                return response()->json(['code' => '001', 'msg' => '结算单没有开始同步，不能结算']);
            }
            //实时计算剩余件数/剩余重量
            $one['residue_weight'] = mathfuncweight('div',($one['sale_weight'] - $one['sales_weight']),10000, 4);
            $one['residue_pieces'] = $one['sale_pieces'] - $one['sales_pieces'];
        }

        //获取账套下的结算规则
        $memberinfo = $this->mangerinfo;
        $cpid = $memberinfo['cpid'] ?? 0;
        $salerule = Salerule::where('cpid', $cpid)->first();
        if (!$salerule) {
            return response()->json(['code' => '001', 'msg' => '结算规则不存在']);
        }

        /***
         * 1.符合规则，直接结束
         * 2.超过规则上下限,进入审核状态，审核通过后 可结束。
         * 王丹娜 2025.04.01
         *
        */
        $salerule = $salerule->toArray();
        $pieces_min = $salerule['pieces_min'];
        $pieces_max = $salerule['pieces_max'];
        $weight_min = $salerule['weight_min'];
        $weight_max = $salerule['weight_max'];

        //剩余件数
        $one['residue_pieces'] = $one['sale_pieces'] - $one['sales_pieces'];
        //剩余重量
        $one['residue_weight'] = $one['sale_weight'] - $one['sales_weight'];

        //是否经过审核，如果审核通过 直接结束
        $is_need_audit = false;
        if (
            $one['residue_pieces'] > $pieces_max
            || $one['residue_weight'] > $weight_max
            || $one['residue_pieces'] < $pieces_min
            || $one['residue_weight'] < $weight_min
        ){
            $is_need_audit = true;
        }
        //需要审核，未审核
        if($is_need_audit && $one['status'] != '4'){
            $status = 2;
            $settle_status = 1;
            $is_audit = 2;
            Saleimplementation::where(['id' => $id])->update(['status' => $status, 'settle_status' => $settle_status,'cp_mid'=>$memberinfo['id'],'is_audit'=>$is_audit]);
            return response()->json(['code' => '001', 'msg' => '订单结束差额较大,进入操盘审核']);
        }
        //不需要审核,审核通过
        $settle_status = 2;
        /***
         * 订单剩余金额不需要返还，直接按照结算单返还
         *
         * 点价订单，回调扣除。其他订单 比对结算单直接返还
         *
        */
//        $amout = $one['sale_amount'] - $one['taxamount_total'];
//        Balance::where(['custom_id' => $one['custom_id']])->update([
//            'balance' => DB::raw('balance + ' . $amout)
//        ]);

        $saleInvoice = TplusSaleInvoice::where(['order_number'=>$one['order_number'],'cpid'=>$cpid])->get();

        //减去销售订单号，销售结算单金额
        foreach ($saleInvoice as $item){
            $current_money = TplusSaleInvoiceInfo::where('main_id',$item['id'])->sum('OrigTaxAmount');
            Balance::where(['custom_id' => $one['custom_id']])->update([
                'balance' => DB::raw('balance - ' . $current_money)
            ]);
        }
        //加上原来扣除的用户余额
        $Salesorder = Salesorder::where(['is_del'=>'1','order_number'=>$one['order_number'],'cpid'=>$cpid])->get();
        if($Salesorder){
            foreach ($Salesorder as $sales){
                $current_sales_amount = Salesordersub::where(['is_del'=>'1','cpid'=>$cpid,'p_id'=>$sales['id']])->sum('total');
                Balance::where(['custom_id' => $one['custom_id']])->update([
                    'balance' => DB::raw('balance + ' . $current_sales_amount)
                ]);
            }
        }
        /****
         *  根据程阳要求，销售订单执行表，点击结束按钮，
         *  比对 销售订单和出库单，销售订单锁多了的钢材，进行归还。
         *  此逻辑有疑问，有问题的话就注释掉。
         *
         *  目前根据订单执行表剩余量更新，如果按照 出库单释放，假设发货单未出库时，结束。导致多释放
         *  2025.07.11
         *
        */
        $returnLockedStock = $this->returnLockedStock($one,new SaleorderController($request));
        if($returnLockedStock['code'] == '001'){
            return response()->json($returnLockedStock);
        }

        Saleimplementation::where(['id' => $id])->update(['status' => '1', 'settle_status' => $settle_status]);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 客户余额
     */
    public function custombalance(Request $request)
    {
        $memberinfo = $this->mangerinfo;
        $isgetall = $request->isgetall ?? 0;
        $list = Saleimplementation::custombalance($request, $memberinfo, $isgetall);
        // if ($list['list']) foreach ($list['list'] as $key => $value) {
        //     $list['list'][$key]['sale_amount'] = $list['list'][$key]['sale_amount'] / 100;
        // }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    public function handlestatus(Request $request)
    {
        $params = ['id', 'status'];
        $req_data = $request->only($params);

        $id = $req_data['id'];
        $one = Saleimplementation::where('id', $id)->first();
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        } else {
            $one = $one->toArray();
            if ($one['is_sync'] == 1) {
                return response()->json(['code' => '001', 'msg' => '结算单没有开始同步，不能结算']);
            }
        }
        /***
         *  通过 status=4 驳回 status=3
         *
        */
       if(!in_array($req_data['status'],['3','4'])){
           return response()->json(['code' => '001', 'msg' => '当前审核操作异常']);
       }
        $data = [
            'status' => $req_data['status'],
            'update_at' => time()
        ];
        Saleimplementation::where('id', $id)->update($data);
        return response()->json(['code' => '000', 'msg' => '审核完成']);
    }
    /***
     * 执行表结束，未出库钢材释放 可用重量/可用件数。
     *
     * 销售订单-销货单
     *
    */
    public function returnLockedStock($data,$saleorderController){
        $res = ["code" => "001","msg"=> ""];
        if(!isset($data['order_number']) || !isset($data['cpid'])){
            $res['msg'] = "销售订单执行表数据异常，请重试";
            return $res;
        }
        $Saleimplementationsub = Saleimplementationsub::where(['p_id'=>$data["id"],'is_del'=>'1'])->get();
        $stock_data = [];
        foreach ($Saleimplementationsub as $item){
            $Saleordersub = Saleordersub::where(['id'=>$item["sale_id"],"is_del"=>"1"])->first();
            $stock_data[] = [
                'total_weight' => $item["sale_weight"] - $item["sales_weight"],
                'pieces' => $item["sale_pieces"] - $item["sales_pieces"],
                'stock_id' => $Saleordersub['stock_id'],
            ];
        }
        $res = $saleorderController->incrDecrStockInSaleEdit($stock_data,'incr');
        return $res;
    }
}
